<template>
  <div :data-id="item.id"  class="wb-text" @click="onClickText">
    <p v-if="commonAttr.isHtml" ref="textarea" class="wid-hei-inherit overflow-hidden" :style="styles" v-html="getCommonAttrText"></p>
    <p v-else-if="commonAttr.isSplitGsap || commonAttr.isVertical || commonAttr.isPLable" ref="textarea" class="split-text-gsap wid-hei-inherit overflow-hidden" :data-id="item.id" :style="styles"> {{ getCommonAttrText }} </p>
    <van-field
      v-else
      :center="true"
      :border="false"
      type="textarea"
      ref="textarea"
      :maxlength="commonAttr.limitTextNum ? commonAttr.limitTextNum : 1000"
      :placeholder="commonAttr.placeholder"
      :readonly="isH5Edit ? false : !commonAttr.isEdit"
      v-model="getCommonAttrText"
      :style="styles"
      @input="updateFormValue"
    ></van-field>
    <span class="need-cls font-size-24" v-show="item.commonAttr.need && item.commonAttr.isShowNeed">*</span>
  </div>
</template>

<script>
import { utils } from '@/components/utils/utils'
import { commonUtils } from '@/components/utils/common-utils'
import { EventBus } from '@/store/index'
import { COMPONENT_TYPES, CONTROL_TYPES } from '@/common/const-wb'
import { replaceStr, testGuid, getCompIdByParam, isJSON } from '@/plugins/utils'
import { ref } from 'vue'
import { getPxOVwByValue } from '@/store/utils'
import { EVENT_HOVER_TYPES } from '@/common/events'

export default {
  mixins: [utils, commonUtils],
  setup () {
    return {
      commonAttrText: ref(''),
      isReplaceByCompId: false,
      placeholerColor: '',
      textarea: null,
      isRefresh: false,
    }
  },
  created() {
    this.refreshCommonAttrText()
    if(this.isH5Edit){
      return
    }
    /* eslint-disable */
    let compIds = this.commonAttr.text.match(/\$[^\$]+\$/g);
    if(_.isArray(compIds)){
      for(let i = 0, len = compIds.length; i < len; i++){
        let compIds_ = compIds[i];
        let compId = getCompIdByParam(compIds_);
        if(compId && testGuid(compId)){
          this.isReplaceByCompId = true;
          break;
        }
      }
    }
    // }else{
    //   let compId = getCompIdByParam(compIds);
    //   if(compIds && compIds.length > 0 && (testGuid(compIds) || testGuid(compId))){
    //     this.isReplaceByCompId = true;
    //   }
    // }
    const commonAttr = this.commonAttr;
    let relateAttrCompId = getCompIdByParam(commonAttr.relateAttrCompId);
    if(commonAttr.isDynamic || commonAttr.isRandom || commonAttr.dataKey || relateAttrCompId || this.numberItemData && !this.isDisplayVoteOrNumberBtn){
      this.isRefresh = true;
      EventBus.$off("refreshDynamicData", this.refreshCommonAttrText)
      EventBus.$on("refreshDynamicData", this.refreshCommonAttrText)
    }
    if(this.isReplaceByCompId){
      EventBus.$off("refreshBindText", this.onRefreshBindText)
      EventBus.$on("refreshBindText", this.onRefreshBindText)
    }
  },
  computed: {
    isDisplayVoteOrNumberBtn(){
      let text = this.commonAttr.text;
      let attrName = this.getAttrNameByParam(text);
      if(this.item.cid == COMPONENT_TYPES.wb_text && attrName && attrName.length > 0){
        return false;
      }else{
        return true;
      }
    },
    getCommonAttrText: {
      get(){
        let commonAttr = this.commonAttr;
        let txt = commonAttr.text;
        if(this.commonAttr.isHtml){
          txt = txt.replace(/《/g, "<");
          txt = txt.replace(/》/g, ">");
        }
        if(!this.isH5Edit){
          //relateAttrCompId 站点id 655 新年许愿管
          if(commonAttr.isRandom){
            if(txt) {
              const arr = txt.split(",");
              if(arr.length > 1) {
                txt = _.random(arr[0], arr[1]);
              }
            }
          }else if(this.isRefresh){
            txt = this.commonAttrText;
          }else{
            if(this.isReplaceByCompId){
              txt = replaceStr(this.formValues, txt);
              this.commonAttrText = txt
              this.$store.commit('updateFormValue', { id: this.item.id, value: this.commonAttrText })
              // this.$store.dispatch("updateComponentAttr", {id:this.item.id, commonAttr: { text: txt }});
            }
          }
        }
        return txt
      },
      set(value){
        this.onChange(value)
      }
    }
  },
  mounted(){
    let dom = this.$refs.textarea && this.$refs.textarea.$el;
    this.textarea = dom && dom.getElementsByClassName("van-field__control")[0];
    if(this.textarea){
      this.refreshPlaceholerColor();
    }
    if(!this.commonAttr.isHtml){
      this.gradientText()
      this.textShadow()
      this.updateScrollY()
    }
    if(this.isH5Edit){
      return
    }
    if(this.commonAttr.isEdit && !this.commonAttr.need){
      this.$store.commit('updateFormValue', {id:this.item.id, value: this.commonAttr.text || this.commonAttr.placeholder})
    }
    this.convertCustomCss()
  },
  methods: {
    getCompDom() {
      let commonAttr = this.commonAttr;
      if(commonAttr.isHtml || commonAttr.isSplitGsap || commonAttr.isVertical || commonAttr.isPLable) {
        return this.$refs.textarea
      } else {
        return this.$refs.textarea && this.$refs.textarea.$el
      }
    },
    updateFormValue(e){
      // this.inputValue_ = e.target.value
      let value;
      if(e){
        value = e.target.value;
      }else if(this.commonAttr.value && this.commonAttr.value.length > 0){
        value = this.commonAttr.value;
      }
      if(!this.isH5Edit){
        this.$store.commit('updateFormValue', { id:this.item.id, value })
      }
    },
    onClickText(e){
      if(this.commonAttr.isEdit){
        e.stopPropagation();
      }
    },
    refreshPlaceholerColor(){
      this.placeholerColor = this.commonAttr.placeholerColor;
      this.addClass(this.textarea, this.placeholerColor);
      if(this.commonAttr.isDisplayY) {
        this.addClass(this.textarea, 'scrollbar');
        this.addClass(this.textarea, this.commonAttr.scrollbarType);
      }
      if(this.commonAttr.isGlow) {
        if(this.commonAttr.glowColor) {
          this.addClass(this.textarea, 'text-glow' + this.commonAttr.glowColor);
        } else {
          this.addClass(this.textarea, 'text-glow');
        }
      }
    },
    onRefreshBindText(){
      let commonAttrText = replaceStr(this.formValues, this.commonAttr.text);
      this.commonAttrText = commonAttrText;
      // this.$store.dispatch("updateComponentAttr", {id:this.item.id, commonAttr: { text: commonAttrText }});
    },
    refreshCommonAttrText(){
      if(this.isH5Edit){
        return
      }
      const commonAttr = this.commonAttr;
      let txt = commonAttr.text;
      if(this.commonAttr.isHtml){
        txt = txt.replace(/《/g, "<");
        txt = txt.replace(/》/g, ">");
      }
      const relateAttrCompId = getCompIdByParam(commonAttr.relateAttrCompId);
      let relateComponentData = this.componentMap[relateAttrCompId];
      let commonAttrText = '';
      let txtDataKey = getCompIdByParam(txt);
      if(commonAttr.dataKey){
        //有 dataKey且有关联组件id，那么就从对应的关联组件id中获取数据 如果没有关联组件，那么就从全局数据中取数据
        if(relateAttrCompId && relateComponentData){
          const namePrefix = commonAttr.namePrefix ? commonAttr.namePrefix : '';
          let name = namePrefix + this.getDataKeyValue(relateComponentData, txt);
          if(commonAttr.nameNum && name.length > commonAttr.nameNum){
            name = name.substring(0, this.commonAttr.nameNum) + '...';
          }
          // 1572 自定义文本 自定义绑定字段为索引+1
          if(txtDataKey == "index"){
            name = parseInt(commonAttr.itemIndex) + 1;
          }
          commonAttrText = name;
        }else if(commonAttr.dataKey == 'custom'){
          commonAttrText = this.getAttrByCustom(this.item, txt);
        }
      }else if(relateAttrCompId && relateComponentData){
        if(relateComponentData.cid == COMPONENT_TYPES.wb_form_score){
          commonAttrText = txt.replace("$" + txtDataKey + "$", this.formValues[relateAttrCompId].data[txtDataKey]);
        }else if(relateComponentData.cid == COMPONENT_TYPES.wb_calendar){
          // 获取签到日历总数
          let elements = this.controls[relateComponentData.id][CONTROL_TYPES.vote].data.elements
          let num = _.filter(elements,item => item.num == 1).length
          commonAttrText = txt.replace("$" + txtDataKey + "$", num);
        }
      }else if(commonAttr.isRandom){
        commonAttrText = txt
      }
      // 动态图片，也可以从图片text中获取键值，或者是默认的shareData中的url
      if(commonAttr.isDynamic && this.shareData.content.toString().length > 0){
        if(this.commonAttr.isHtml){
          txt = this.shareData.content;
          txt = txt.replace(/《br》/g, "<br\>");
          commonAttrText = txt;
        }else{
          commonAttrText = this.shareData.content;
        }
      }
      if(this.commonAttrText !== commonAttrText) {
        if(this.commonAttr.divideNumber){
          let realData =  0
          if(this.commonAttr.divideNumber.indexOf('$') > -1){
            let selfData = 0
            let key = this.commonAttr.divideNumber.replace(/\$/g,'')
            let total = this.bindData[key]
            if(relateComponentData){
              let itemIndex = relateComponentData.commonAttr.itemIndex
              selfData = relateComponentData.lists[itemIndex][txtDataKey]
            }else{
              selfData = commonAttrText
            }
            realData = (selfData / total) * 100
            commonAttrText = txt.replace("$" + txtDataKey + "$", parseInt(realData) );
          }else{
            realData = parseInt(commonAttrText / this.commonAttr.divideNumber)
            commonAttrText = txt.replace("$" + txtDataKey + "$", realData);
          }
          this.$store.commit('updateFormValue', { id: this.item.id, value: realData })
        }else {
          this.$store.commit('updateFormValue', { id: this.item.id, value: commonAttrText })
        }
        if(this.commonAttr.isSeparator){
          // '10000000000'.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
          commonAttrText = commonAttrText.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        }
        this.commonAttrText = commonAttrText
      }
    },
    updateScrollY(){
      if(this.$refs.textarea.$el){
        let textarea = this.$refs.textarea.$el.getElementsByTagName("textarea")[0]
        if(this.commonAttr.isDisplayY){
          textarea.style['overflow-y'] = 'auto'
          textarea.style['padding-right'] = getPxOVwByValue(8)
        }else{
          textarea.style['overflow-y'] = 'hidden'
        }
      }
    },
    onChange(value){
      let text = value ? value : this.commonAttrText;
      if(this.isH5Edit){
        this.$store.dispatch("components/updateCurrentComponentData", {commonAttr: {text}});
      }else{
        if(this.commonAttr.isEdit){
          if(_.keys(this.item.events).length > 0 && this.commonAttr.placeholder && text && this.commonAttr.placeholder != text){
            EventBus.$emit("itemClick", {id: this.item.id, index: 0, e: null});
          }
          this.s = text;
          this.$store.dispatch("updateComponentAttr", {id:this.item.id, commonAttr: {text}});
          this.$store.commit('updateFormValue', {id:this.item.id, value: text})
        }
      }
    },
    gradientText(){
      let commonAttr = this.commonAttr;
      let textarea;
      if(this.$refs.textarea.$el){
        textarea = this.$refs.textarea.$el.getElementsByTagName('textarea')[0];
      }else{
        textarea = this.$refs.textarea
      }
      let styles_ = textarea.style
      if(this.$refs.textarea && commonAttr.isGradient){
        let str = '-webkit-linear-gradient(' + commonAttr.gradientDirection + ', '
        let gradientColors = commonAttr.gradientColors.split(',')
        let len = gradientColors.length
        let base = 1/len * 100

        _.forEach(gradientColors, (color, index) => {
          if(index == len-1){
            str += color + ' ' + index * base + '%'
          }else{
            str += color + ' ' + index * base + '%, '
          }
        })
        str += ')'
        styles_.backgroundImage = str
        styles_['-webkit-background-clip'] = 'text'
        styles_['-webkit-text-fill-color'] = 'transparent'
      }else{
        styles_.backgroundImage = 'none'
        styles_['-webkit-background-clip'] = 'border-box'
        styles_['-webkit-text-fill-color'] = ''
      }
    },
    textShadow() {
      let commonAttr = this.commonAttr;
      if(this.$refs.textarea){
        let textarea;
        if(this.$refs.textarea.$el){
          textarea = this.$refs.textarea.$el.getElementsByTagName('textarea')[0];
        }else{
          textarea = this.$refs.textarea
        }
        let styles_ = textarea.style
        if(commonAttr.textShadowColor){
          let textShadow_ = '0 0 4px ' + commonAttr.textShadowColor + ', -0 -0 2px ' + commonAttr.textShadowColor + ''
          styles_.textShadow = textShadow_
        }else{
          styles_.textShadow = ''
        }
      }
    },
    onRefreshCommonAttr() {
      if(this.commonAttr.isGradient) {
        this.gradientText()
      }
      if(this.commonAttr.textShadowColor) {
        this.textShadow()
      }
      if(this.commonAttr.isDisplayY) {
        this.updateScrollY()
      }
      if(this.placeholerColor != this.commonAttr.placeholerColor && this.textarea) {
        this.refreshPlaceholerColor()
      }
      this.convertCustomCss()
    }
  },
  beforeUnmount(){
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
      return
    }
    if(this.isRefresh){
      EventBus.$off("refreshDynamicData", this.refreshCommonAttrText)
    }
    this.isRefresh = false;
    this.commonAttrText = '';
    if(this.isReplaceByCompId){
      EventBus.$off("refreshBindText", this.onRefreshBindText)
    }
  }
};
</script>
<style lang="scss">
 .wb-text{
  width: inherit;
  height: inherit;
  display: flex;
  align-items: center;

  .van-cell{
    width: inherit;
    height: inherit;
  }

  .van-field__body, .van-cell__value--alone, textarea{
    width: inherit;
    height: inherit;
    line-height: inherit;
    color: inherit;
    background-color: inherit;
    text-align: inherit;
    font-weight: inherit;
    font-style: inherit;
    text-decoration: inherit;
    letter-spacing: inherit;
    font-family: inherit;
    font-size: inherit;
    writing-mode: inherit;
  }

  textarea {
    overflow: hidden;
    overflow-scrolling: touch;
      /* ios 自带滚动条不平滑解决方法 */
    tap-highlight-color: rgba(0, 0, 0, 0);
  }
}

</style>
